/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

//DW/2622/BeginPatch
import opiam.admin.faare.MessageUtil;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;
//DW/2622/EndPatch

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * This actions allows to remove a selected set of elements from the temporary list(the cart).
 *<br>
 * HTTP PARAMETERS :<br>
 * <li>cartname : name of the object to be modified (java.util.List typed)</li>
 * <li>eltindex : multivalued indexes of elements to remove</li>
 */
public class DeleteFromCartAction extends SecureAction
{
    /** Logger de log4j. */
    private static Logger _logger = Logger.getLogger(DeleteFromCartAction.class);

    /**
     * Struts Action method.
     * See SecureAction
     *
     * @param mapping Struts mapping data.
     * @param actionForm Input form.
     * @param request HTTP request.
     * @param httpServletResponse HTTP response.
     *
     * @return forward to success or to error
     *
     * @throws java.io.IOException see Action.execute()
     * @throws javax.servlet.ServletException see Action.execute()
     */
    @Override
	public ActionForward secureExecute(
        ActionMapping mapping,
        ActionForm actionForm,
        HttpServletRequest request,
        HttpServletResponse httpServletResponse)
        throws IOException, ServletException
    {
        String cartname = request.getParameter("cartname");
        String[] elements = request.getParameterValues("eltindex");

        if (elements == null)
        {
            // aucune selection
            request.setAttribute("cartname", cartname);
            return (mapping.findForward("success"));
        }

        _logger.debug("cartname = " + cartname);

        ActionMessages errors = new ActionMessages();

        if ((cartname == null) || cartname.trim().equals(""))
        {
            _logger.error(MessageUtil.getMessageString("MSG_ARGUMENT_NULL"));
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.service.unknown"));
            saveErrors(request, errors);

            return (mapping.findForward("service_error"));
        }

        SessionContext sessionContext = null;
        UserContext userContext = null;

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();
            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);
            // Gets the user context.
            userContext = sessionContext.getUserContext();

            List currentCart = (List) session.getAttribute(cartname);

            if (currentCart != null)
            {
                // save elements to remove, since when we delete, the index change !
                List toRemove = new ArrayList();

                for (int i = 0; i < elements.length; i++)
                {
                    toRemove.add(currentCart.get(Integer.parseInt(elements[i])));
                }

                // now delete
                Iterator it = toRemove.iterator();
                while (it.hasNext())
                {
                    currentCart.remove(it.next());
                }

                if (currentCart.size() == 0)
                {
                	session.removeAttribute(cartname);
                	session.removeAttribute("cartname");
                
                   // Manages the display of the tempList icon
                   boolean indic = userContext.getParameters().containsKey("cartIndic");
                   if (indic)
                   {
                   	 userContext.getParameters().remove("cartIndic");
                   }
                   
                }
            }
            request.setAttribute("cartname", cartname);

            return (mapping.findForward("success"));
        }
        catch (Exception se)
        {
            _logger.debug("Trace", se);
            _logger.error(se.getMessage());
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.service.unknown"));
            saveErrors(request, errors);

            return (mapping.findForward("error"));
        }
    }
}
